package com.demo.service;

import com.demo.entity.Goods;
import com.demo.entity.GoodsSaledFeedBack;
import com.demo.entity.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 处理商品抢购业务
 *
 * @author FCG
 */
@Service
public class SaleService {
    /**
     * logger
     */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 模拟商品秒杀
     * @param goodsList 商品列表
     * @param buyerList 用户列表
     * @return 买家信息更新后的商品列表及耗时
     */
    public GoodsSaledFeedBack sale(List<Goods> goodsList, List<String> buyerList) {
        long start = System.currentTimeMillis();
        Objects.requireNonNull(goodsList, "商品列表不能为空");
        Objects.requireNonNull(buyerList, "用户列表不能为空");
        if (goodsList.size() == 0 || buyerList.size() == 0) {
            return null;
        }
        //已经购买过的用户
        Set<String> buyerIds = goodsList.stream().map(Goods::getBuyerId).collect(Collectors.toSet());
        //未被购买的商品
        List<Goods> rawGoodsList = goodsList.stream().filter((goods) -> goods.getBuyerId() == null).collect(Collectors.toList());
        //用户数
        int n = buyerList.size();
        int i = 0;
        for (Goods goods : rawGoodsList) {
            while (i < n) {
                String buyerId = buyerList.get(i++);
                //商品未被购买，且该用户未购买过此商品
                if (!buyerIds.contains(buyerId)) {
                    goods.setBuyerId(buyerId);
                    logger.debug("用户:{},成功秒杀了商品:{}", buyerId, goods.getGoodsId());
                    break;
                }
            }
        }
        long end = System.currentTimeMillis();
        long timespan = end - start;
        logger.debug("耗时:{} millis", timespan);
        return new GoodsSaledFeedBack(goodsList, timespan);
    }

    /**
     * 处理商品购买过程
     *
     * @param goodsList 商品列表
     * @param orderList 用户列表
     * @return 买家信息更新后的商品列表及耗时
     */
    public GoodsSaledFeedBack buy(List<Goods> goodsList, List<Order> orderList) {
        long start = System.currentTimeMillis();
        Objects.requireNonNull(goodsList, "商品列表不能为空");
        Objects.requireNonNull(orderList, "订单列表不能为空");
        if (goodsList.size() == 0 || orderList.size() == 0) {
            return null;
        }
        //用户数>商品数
        //最终购买用户列表
        List<Order> finalOrders = new ArrayList<>();
        //缓存已购买过的用户id
        Set<String> buyerIds = new HashSet<>();
        //缓存已经被购买的商品id
        Set<String> goodsIds = new HashSet<>();
        //一个商品只能被一个用户购买
        //一个用户只能购买一个商品:按照“用户下单先后顺序”
        for (Order order : orderList) {
            //此用户未被确认购买
            if (!buyerIds.contains(order.getBuyerId()) && !goodsIds.contains(order.getTargetGoodsId())) {
                finalOrders.add(order);
                buyerIds.add(order.getBuyerId());
                goodsIds.add(order.getTargetGoodsId());
            }
        }
        //秒杀后的商品列表
        List<Goods> saledGoodsList = new ArrayList<>();
        //此时，用户数<=商品数
        for (Order order : finalOrders) {
            Iterator<Goods> iter = goodsList.iterator();
            while (iter.hasNext()) {
                Goods goods = iter.next();
                //成功购买
                if (goods.getGoodsId().equals(order.getTargetGoodsId())) {
                    goods.setBuyerId(order.getBuyerId());
                    saledGoodsList.add(goods);
                    iter.remove();
                    logger.debug("用户:{},成功秒杀了商品:{}", order.getBuyerId(), goods.getGoodsId());
                    break;
                }
            }
        }
        //剩余商品
        saledGoodsList.addAll(goodsList);
        long end = System.currentTimeMillis();
        long timespan = end - start;
        logger.debug("耗时:{} millis", timespan);
        return new GoodsSaledFeedBack(saledGoodsList, timespan);

    }
}
